#!/usr/bin/env ruby

require 'tempfile'
require 'socket'

ADDR = 'socket'.freeze

def main(gitaly_dir)
  gitaly_dir = File.realpath(gitaly_dir)

  Dir.mktmpdir do |dir|
    Dir.chdir(dir)

    File.write('config.toml', <<~CONFIG
      socket_path = "#{ADDR}"
      bin_dir = "#{gitaly_dir}"

      [[storage]]
      name = "default"
      path = "#{dir}"

      [gitaly-ruby]
      dir = "#{gitaly_dir}/ruby"

      [gitlab-shell]
      dir = "#{gitaly_dir}"
      CONFIG
              )

    pid = nil

    begin
      start = Time.now
      pid = spawn(File.join(gitaly_dir, 'gitaly'), 'config.toml')
      wait_connect
      puts
      puts "\n\nconnection established after #{Time.now - start} seconds\n\n"
    ensure
      if pid
        Process.kill("KILL", pid)
        Process.wait(pid)
      end
    end
  end
end

def wait_connect
  loop do
    begin
      Socket.unix(ADDR)
      return
    rescue # rubocop:disable Lint/RescueWithoutErrorClass
      print '.'
      sleep(0.1)
    end
  end
end

unless ARGV.count == 1
  abort "Usage: #{$PROGRAM_NAME} GITALY_DIR"
end

main(ARGV.first)
